<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j shop-contianer page-shop-index">
    <div class="shop-index">
      <div class="shop-head-wrap">
        <div class="shop-head">
          <div class="shop-logo">
            <div class="img">
              <img-show :src="shopInfo.shopLogo" />
            </div>
            <div class="text">
              <div class="name">
                {{ shopInfo.shopName }}
              </div>
              <div class="operation">
                <div
                  v-if="shopInfo.shopId === 1"
                  class="self"
                >
                  {{ $t('shopInfo.selfShop') }}
                </div>
                <div
                  v-else
                  class="self"
                >
                  {{ shopInfo.type === 1 ? $t('shopInfo.preferredStores') : $t('shopInfo.generalStore') }}
                </div>
                <div
                  class="favourite"
                  :class="{ active: isCollection }"
                  @click="shopCollection()"
                >
                  <i class="icon" />
                  {{ isCollection ? $t('shopInfo.followed') : $t('shopInfo.follow') }}
                </div>
                <div
                  class="favourite last-favourite"
                  @click="onToQualifications()"
                >
                  <img
                    src="@/assets/images/qualifications.png"
                    style="width: 16px;height: 16px;margin-right: 5px;"
                    alt=""
                  >
                  <span>{{ $t('shopInfo.qualifications') }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="shop-news">
            <div class="news-tit">
              <div class="tit">
                {{ $t('storeAnnouncement') }}
              </div>
              <div
                v-if="noticeList.length"
                class="more"
                @click="toNewsList"
              >
                {{ $t('more') }}&nbsp;&nbsp;
              </div>
            </div>
            <div
              v-if="noticeList.length"
              class="news-list-con"
            >
              <div
                v-for="(news, index) in noticeList"
                :key="index"
                class="news-item"
                @click="toNewsDet(news.id)"
              >
                {{ news.title }}
              </div>
            </div>
            <div
              v-else
              class="news-empty"
            >
              {{ $t('shopInfo.noAnnouncement') }}
            </div>
          </div>
        </div>
      </div>
      <div class="mian-content">
        <div class="content">
          <div class="title">
            {{ $t('shopInfo.StoreOperators') }}
          </div>
          <div class="article-wrap">
            <div class="article-lines">
              <span class="sidehead">
                {{ $t('shopInfo.EnterpriseName') }}：
              </span>
              <span class="txt">
                {{ businessForm.firmName }}
              </span>
            </div>
            <div class="article-lines">
              <span class="sidehead">
                {{ $t('shopInfo.licenseNumber') }}：
              </span>
              <span class="txt">
                {{ businessForm.creditCode }}
              </span>
            </div>
            <div class="article-lines">
              <span class="sidehead">
                {{ $t('shopInfo.EnterpriseResidence') }}：
              </span>
              <span class="txt">
                {{ businessForm.residence ? businessForm.residence : '暂无' }}
              </span>
            </div>
            <div class="article-lines">
              <span class="sidehead">
                {{ $t('shopInfo.legalRepresentative') }}：
              </span>
              <span class="txt">
                {{ businessForm.representative }}
              </span>
            </div>
            <div class="article-lines">
              <span class="sidehead">
                {{ $t('shopInfo.registeredCapital') }}：
              </span>
              <span class="txt">
                {{ businessForm.capital ? businessForm.capital + '万元' : '暂无' }}
              </span>
            </div>
            <div class="article-lines">
              <span class="sidehead">
                {{ $t('shopInfo.establishmentAata') }}：
              </span>
              <span class="txt">
                {{ businessForm.foundTime ? timerHandler(businessForm.foundTime) : '暂无' }}
              </span>
            </div>
            <div class="article-lines">
              <span class="sidehead">
                {{ $t('shopInfo.businessTerm') }}：
              </span>
              <span class="txt">
                <span v-if="businessForm.startTime && businessForm.endTime">
                  {{ timerHandler(businessForm.startTime) + ' - ' + timerHandler(businessForm.endTime) }}
                </span>
                <span v-else-if="businessForm.startTime">
                  {{ timerHandler(businessForm.startTime) + ' - ' + $t('shopInfo.noFixedTerm') }}
                </span>
                <span v-else>
                  {{ $t('shopInfo.notYet') }}
                </span>
              </span>
            </div>
            <div class="article-lines">
              <span class="sidehead">
                {{ $t('shopInfo.businessScope') }}：
              </span>
              <span class="txt">
                {{ businessForm.businessScope }}
              </span>
            </div>
            <div class="article-lines img-wrap">
              <img-show
                :src="businessForm.businessLicense"
                :class-list="['img-box']"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import { ElMessage } from 'element-plus'
const route = useRoute()
const router = useRouter()
const langStore = useLanguageStore()

// 监听id，要是发生变化就重新请求数据
watch(() => route.query, (to, from) => {
  // 路由变话页面刷新
  if (to.sid === from.sid) {
    langStore.handleShopRouter(to)
    return
  }
  location.reload()
}, { deep: true })

const shopId = ref(route.query.sid || 0)
onMounted(() => {
  document.title = $t('shopInfo.qualifications')
  // 将滚动条置顶
  window.scrollTo(0, 0)
  getPageData()
  getInfo()
  init()
  if (!shopId.value) {
    ElMessage({
      message: $t('userCenter.theStoreOffline'),
      duration: 1000,
      type: 'warning'

    })
  }
})

const businessForm = ref({})
const init = () => {
  http.request({
    url: '/shopCompany/' + shopId.value,
    method: 'GET'
  })
    .then(({ data }) => {
      businessForm.value = data
    })
}

/**
 * 时间处理器
 * y-m-n x:x:x => y年m月n日
 * @param timer
 * @returns {*|string}
 */
const timerHandler = (timer) => {
  if (!timer) return timer
  timer = timer.slice(0, -8).trim().split('-')
  return timer[0] + '年' + timer[1] + '月' + timer[2] + '日'
}

const categoryId = ref('')
const prodName = ref('')
const current = ref(1)
/**
 * pn: 商品名称
 * cid: 店铺分类id
 * sid: 店铺id
 * sort: 根据默认(0)/销量(1)/价格(2)排序
 * size: 每页的数据数量
 * ob: 0正序 1倒序
 * c: 当前第几页
 */
const getPageData = () => {
  const query = route.query
  getaHeadInfo(query)
  getNoticeList(query)
  if (Cookie.get('bbcToken')) {
    getUserCollection()
  }
  categoryId.value = query.cid ? query.cid : ''
  prodName.value = query.pn
  current.value = query.c ? query.c : 1
}

const categoryList = ref([])
const categoryName = ref('') // 获取店铺分类信息

const noticeList = ref([])
const getNoticeList = (query) => {
  let path = '/notice/noticeList/'
  if (Cookie.get('bbcToken')) {
    path = '/p/notice/noticeList/'
  }
  http.get(path + query.sid, {
    // 店铺公告
    params: {
      current: 1, // 当前页
      size: 2
    }
  }).then(({ data }) => {
    noticeList.value = data.records
  }).catch(() => {})
}

const shopInfo = ref({}) // 获取店铺头部信息
// 获取店铺头部信息
const getaHeadInfo = (query) => {
  http.get('/shop/headInfo', {
    // 店铺头部信息
    params: {
      shopId: query.sid
    }
  }).then(({ data }) => {
    shopInfo.value = data
    handleShopStatus()
  }).catch(() => {})
}
/**
 * 店铺状态处理
 */
const handleShopStatus = () => {
  const shopStatus = shopInfo.value.shopStatus
  // 未开通/已删除
  if (shopStatus === -1) {
    ElMessage({
      type: 'warning',
      message: $t('collection.storeReviewTips2'),
      duration: 1000,
      onClose: () => {
        router.push({ path: '/' })
      }
    })
    return
  }
  // 停业中
  if (shopStatus === 0) {
    const contractStartTime = new Date(shopInfo.value.contractStartTime).getTime()
    const contractEndTime = new Date(shopInfo.value.contractEndTime).getTime()
    const today = new Date().getTime()
    // 1、店铺状态为0(停业中)时，当店铺未到签约开始时间，用户进入店铺提示：商家尚未营业
    if (today < contractStartTime) {
      ElMessage({
        type: 'warning',
        message: $t('collection.storeReviewTips4'),
        duration: 1000,
        onClose: () => {
          router.push({ path: '/' })
        }
      })
      return
    }
    // 2、店铺状态为0(停业中)时，当店铺超过签约有效期，用户进入店铺提示：商家已暂停未营业
    if (today > contractEndTime) {
      ElMessage({
        type: 'warning',
        message: $t('collection.storeReviewTips5'),
        duration: 1000,
        onClose: () => {
          router.push({ path: '/' })
        }
      })
      return
    }
  }
  // 已下线
  if (shopStatus === 2 || shopStatus === 3) {
    ElMessage({
      type: 'warning',
      message: $t('collection.storeReviewTips3'),
      duration: 1000,
      onClose: () => {
        router.push({ path: '/' })
      }
    })
  }
}

/**
 * 跳转公告详情
 */
const toNewsDet = (id) => {
  router.push({
    path: '/notice-detail',
    query: {
      id,
      shopId: shopId.value,
      shopName: shopInfo.value.shopName
    }
  })
}

/**
 * 跳转公告列表
 */
const toNewsList = () => {
  router.push({
    path: '/notice-list',
    query: {
      shopId: shopId.value,
      shopName: shopInfo.value.shopName
    }
  })
}

/**
 * 获取店铺信息
 */
const getInfo = () => {
  if (!route.query.sid) {
    shopId.value = shopInfo.value.shopId
  }
  if (categoryId.value) {
    categoryList.value.forEach(category => {
      if (categoryId.value === category.categoryId.toString()) {
        categoryName.value = category.categoryName
      }
    })
  }
}

const isCollection = ref(false)
/**
 * 获取用户是否收藏此店铺
 */
const getUserCollection = () => {
  http.get('/p/shop/collection/isCollection', {
    params: {
      shopId: shopId.value
    }
  })
    .then(({ data }) => {
      isCollection.value = data
    })
}

/**
 * 收藏店铺/取消收藏
 */
const shopCollection = () => {
  http.post('/p/shop/collection/addOrCancel', shopId.value).then(({ data }) => {
    if (data) {
      ElMessage({
        message: $t('prodDetail.collectionSuccess'),
        type: 'success',
        duration: 1000
      })
    } else {
      ElMessage({
        message: $t('prodDetail.uncollected'),
        duration: 1000
      })
    }
    getUserCollection()
  })
}

/**
 * 去往 资质证照 页面
 */
const onToQualifications = () => {
  router.push({
    path: '/shop-qualifications',
    query: {
      sid: shopId.value
    }
  })
}
</script>

<style lang="scss" scoped>
@use "index";
</style>
